package cn.ifavor.googleplay.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

public class RatioLayout extends FrameLayout {

	private static final String ATTRIBUTE_RATIO = "ratio";
	private static final String NAMESPACE = "http://schemas.android.com/apk/res/cn.ifavor.googleplay";
	
	private float ratio = 2.43f;

	public RatioLayout(Context context) {
		super(context);
		init(null);
	}

	public RatioLayout(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(attrs);
	}

	public RatioLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(attrs);
	}

	private void init(AttributeSet attrs) {
		if (attrs != null){
			float attributeRatio= attrs.getAttributeFloatValue(NAMESPACE, ATTRIBUTE_RATIO, 2.43f);
			setRatio(attributeRatio);
		}
	}

	
	public float getRatio() {
		return ratio;
	}

	public void setRatio(float ratio) {
		this.ratio = ratio;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		int width = widthSize - getPaddingLeft() - getPaddingRight();

		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int heightSize = MeasureSpec.getSize(heightMeasureSpec);
		int height = heightSize - getPaddingTop() - getPaddingBottom();

		if (widthMode == MeasureSpec.EXACTLY
				&& heightMode != MeasureSpec.EXACTLY) {
			height = (int) (width / ratio);
		} else if (widthMode != MeasureSpec.EXACTLY
				&& heightMode == MeasureSpec.EXACTLY) {
			width = (int) (height * ratio);
		}

		widthMeasureSpec = MeasureSpec.makeMeasureSpec(width + getPaddingLeft()
				+ getPaddingRight(), MeasureSpec.EXACTLY);
		heightMeasureSpec = MeasureSpec.makeMeasureSpec(height
				+ getPaddingTop() + getPaddingBottom(), MeasureSpec.EXACTLY);

		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

}
